package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.AddImageAdapter;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.CustomAddition;
import com.hemaapp.yjnh.bean.CustomBlogDetail;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.Reply;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.view.ImageGridView;
import com.hemaapp.yjnh.view.NumberSelectorLayout;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xtom.frame.util.XtomToastUtil;

public class CustomizeConfirm1Activity extends BaseActivity {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.tv_send_date)
    TextView tvSendDate;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.layout_number_selector)
    NumberSelectorLayout numberSelector;
    @Bind(R.id.tv_total_1)
    TextView tvTotal1;
    @Bind(R.id.layout_additions)
    LinearLayout layoutAdditions;
    @Bind(R.id.tv_total_2)
    TextView tvTotal2;
    @Bind(R.id.tv_submit)
    TextView tvSubmit;

    private String blogId = "";
    private CustomBlogDetail blog;
    private int buyCount = 1;
    private double price = 0;
    private double additionFee = 0;
    private String additionIds = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_customize_confirm);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        if (blog == null) {
            XtomToastUtil.showShortToast(mContext, "数据异常,请稍后再试");
            finish();
        }else
            initProduction();
//        if (isNull(blogId) || blogId.equals("0")) {
//            XtomToastUtil.showShortToast(mContext, "数据异常,请稍后再试");
//            finish();
//        }else {
//            User user = getApplicationContext().getUser();
//            String token = user == null?"":user.getToken();
//            getNetWorker().getCustomBlog(token, blogId);
//        }
    }

    @Override
    protected void getExras() {
        blogId = mIntent.getStringExtra("blog_id");
        blog = (CustomBlogDetail) mIntent.getSerializableExtra("blog");
    }

    @Override
    protected void setListener() {
        titleRightBtn.setVisibility(View.GONE);
        titleText.setText("立即订制");
        numberSelector.setNumberSelectorListener(new NumberSelectorLayout.NumberSelectorListener() {
            @Override
            public void onNumberChanged(int curValue) {
                buyCount = curValue;
                refreshTotalFee();
            }
        });
        numberSelector.setMaxValue(1000);
    }

    @OnClick({R.id.title_left_btn, R.id.tv_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.tv_submit:
                if (buyCount < 1) {
                    XtomToastUtil.showShortToast(mContext, "请输入购买数量");
                    break;
                }
                Intent it = new Intent(mContext, CustomizeConfirm2Activity.class);
                it.putExtra("blog", blog);
                it.putExtra("buycount", buyCount);
                it.putExtra("additionFee", additionFee);
                it.putExtra("addition_ids", additionIds);
                startActivity(it);
                finish();
                break;
        }
    }

    private void initProduction() {
        if (blog.getSend_date().equals("0000-00-00"))
            tvSendDate.setText("该定制产品未提供发货日期");
        else
            tvSendDate.setText("该定制产品发货日期："+blog.getSend_date());
        tvName.setText(blog.getName());
        tvPrice.setText("¥"+uuUtils.formatAfterDot2(blog.getPrice()));
        price = Double.parseDouble(blog.getPrice());
        addAddtitons();
        refreshTotalFee();
    }

    private void addAddtitons() {
        ArrayList<CustomAddition> additions = (ArrayList<CustomAddition>) blog.getAddItems();
        boolean hasAdditon = false;
        for (CustomAddition addition : additions) {
            if (addition.isChecked()) {
                View view  = LayoutInflater.from(mContext).inflate(
                        R.layout.item_custom_detail_addition, null);
                ViewHolder2 holder2= new ViewHolder2(view);
                holder2.setDatas(addition);
                additionFee += Double.parseDouble(addition.getPrice());
                additionIds = additionIds+addition.getId()+",";
                layoutAdditions.addView(view);
                hasAdditon = true;
            }
        }
        if (additionIds.length() > 0)
            additionIds = additionIds.substring(0, additionIds.length()-1);
        if (!hasAdditon)
            layoutAdditions.setVisibility(View.GONE);
    }

    private void refreshTotalFee() {
        DecimalFormat df = new DecimalFormat("0.00");
        double totalfee = buyCount*price;
        tvTotal1.setText("¥"+df.format(totalfee));

        totalfee += additionFee;
        tvTotal2.setText("¥"+df.format(totalfee));
    }

    class ViewHolder2 {
        @Bind(R.id.tv_price)
        TextView tvPrice;
        @Bind(R.id.tv_content)
        TextView tvContent;
        @Bind(R.id.iv_select)
        ImageView ivSelect;
        @Bind(R.id.image_grid)
        ImageGridView imageGridView;
        int position = -1;
        AddImageAdapter imageAdapter;
        ArrayList<ImgItemsBean> additonImg = new ArrayList<>();

        ViewHolder2(View view) {
            ButterKnife.bind(this, view);
            ivSelect.setVisibility(View.GONE);
        }

        private void setDatas(CustomAddition addition) {
            tvPrice.setText("¥"+uuUtils.formatAfterDot2(addition.getPrice()));
            tvContent.setText(addition.getContent());
            additonImg.addAll(addition.getImgItems());
            refreshImages();
        }

        private void refreshImages() {
            if (imageAdapter == null) {
                imageAdapter = new AddImageAdapter(mContext, additonImg);
                imageGridView.setAdapter(imageAdapter);
                imageAdapter.setShowDelete(false);
                imageAdapter.setShowAdd(false);
                imageAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                    @Override
                    public void onImageClickListener(int position) {
                        ArrayList<Img> imgs = new ArrayList<Img>();
                        for (int i = 0; i < additonImg.size(); i++) {
                            ImgItemsBean item = additonImg.get(i);
                            String imgurl_detail = item.getImgurlbig();
                            Img img = new Img(imgurl_detail);
                            imgs.add(img);
                        }

                        Intent intent = new Intent();
                        intent.setClass(mContext, ShowLargeImageActivity.class);
                        intent.putExtra("imgs", imgs);
                        intent.putExtra("position", position + 1);
                        mContext.startActivity(intent);
                    }

                    @Override
                    public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                    }
                });
            } else {
                imageAdapter.notifyDataSetChanged();
            }
        }
    }
    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
                HemaArrayResult<CustomBlogDetail> bResult = (HemaArrayResult<CustomBlogDetail>) baseResult;
                blog = bResult.getObjects().get(0);
                if (blog == null) {
                    XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍候再试");
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            finish();
                        }
                    }, 2000);
                } else {
                    initProduction();
                }
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，" + baseResult.getMsg());
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍候再试");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
                break;
        }
    }
}
